--
--  Copyright (c) 2016, Facebook, Inc.
--  All rights reserved.
--
--  This source code is licensed under the BSD-style license found in the
--  LICENSE file in the root directory of this source tree. An additional grant
--  of patent rights can be found in the PATENTS file in the same directory.
--
require 'torch'
require 'paths'
require 'optim'
require 'nn'
require 'orn'
require 'cuorn'
require 'inn'

local DataLoader = require 'dataloader'
local models = require 'models/init'
local Trainer = require 'train'
local opts = require 'opts'
local checkpoints = require 'checkpoints'

-- we don't  change this to the 'correct' type (e.g. HalfTensor), because math
-- isn't supported on that type.  Type conversion later will handle having
-- the correct type.
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(1)

local opt = opts.parse(arg)
torch.manualSeed(opt.manualSeed)
cutorch.manualSeedAll(opt.manualSeed)

-- Load previous checkpoint, if it exists
local checkpoint, optimState = checkpoints.latest(opt)

-- Create model
local model, criterion = models.setup(opt, checkpoint)

-- Data loading
local trainLoader, valLoader = DataLoader.create(opt)

-- The trainer handles the training loop and evaluation on validation set
local trainer = Trainer(model, criterion, opt, optimState)

-- if opt.testOnly then
--    local top1Err, top5Err, testLoss = trainer:test(0, valLoader)
--    print(string.format(' * Results top1: %6.3f  top5: %6.3f', top1Err, top5Err))
--    print(string.format(' * Results top1: %7.3f  top5: %7.3f', top1Err, top5Err))
--    return
-- end

if opt.testOnly then
   local cams, pred = trainer:cam(0, valLoader)
   torch.save('cams-sp-gt.t7', cams)
   -- torch.save('pred-sp-top5.t7', pred)   
   -- local matio = require 'matio'
   -- matio.save('cams.mat', cams)

   print('Done.')
end

local startEpoch = checkpoint and checkpoint.epoch + 1 or opt.epochNumber
local bestTop1 = math.huge
local bestTop5 = math.huge
local timer = torch.Timer()
for epoch = startEpoch, opt.nEpochs do
   -- Train for a single epoch
   local trainTop1, trainTop5, trainLoss = trainer:train(epoch, trainLoader)
   print(string.format('Epoch %d | Time %.2f | trainLoss %1.4f | trainTop1 %7.3f | trainTop5 %7.3f',
      epoch, timer:time().real,
      trainLoss, trainTop1, trainTop5))
   timer:reset()

   -- Run model on validation set
   local testTop1, testTop5, testLoss = trainer:test(epoch, valLoader)

   print(string.format('Epoch %d | Time %.2f | testLoss %1.4f | testTop1 %7.3f | testTop5 %7.3f',
      epoch, timer:time().real, 
      testLoss, testTop1, testTop5))
   local bestModel = false
   if testTop1 < bestTop1 then
      bestModel = true 
      bestTop1 = testTop1
      bestTop5 = testTop5
      print(' * Best model ', testTop1, testTop5)
   end

   checkpoints.save(epoch, model, trainer.optimState, bestModel, opt)
   timer:reset()
end

print(string.format(' * Finished top1: %6.3f  top5: %6.3f', bestTop1, bestTop5))
